package com.haixiaoke.saas.common.utils.sign;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * AES加密方法
 */
public class AesUtils {
    private static final Logger log = LoggerFactory.getLogger(AesUtils.class);

    /**
     * 对明文使用指定Key加密 生成32位16进制
     *
     * @param plainText 明文
     * @param password  秘钥
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String plainText, String password) throws Exception {
        String key = generateKey(password);
        // 对明文进行加密
        return encrypt(plainText, key);
    }

    /**
     * 对密文使用指定Key解密
     *
     * @param cipherText 密文
     * @param password   秘钥
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String cipherText, String password) throws Exception {
        String key = generateKey(password);
        // 密文解密
        return decrypt(cipherText, key);
    }

    // 生成32位16进制密钥
    public static String generateKey(String password) throws NoSuchAlgorithmException {
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
        byte[] key = sha256.digest(password.getBytes());
        return DatatypeConverter.printHexBinary(key).substring(0, 32);
    }

    // 对明文进行加密
    public static String encrypt(String plainText, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] cipherText = cipher.doFinal(plainText.getBytes());
        return DatatypeConverter.printHexBinary(cipherText);
    }

    // 对密文进行解密
    public static String decrypt(String cipherText, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] plainText = cipher.doFinal(DatatypeConverter.parseHexBinary(cipherText));
        return new String(plainText);
    }
}
